package com.lei.baweiliao.view.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.hyphenate.EMContactListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.exceptions.HyphenateException;
import com.lei.baweiliao.R;
import com.lei.baweiliao.bean.UserBean;
import com.lei.baweiliao.bean.UserInfo;
import com.lei.baweiliao.db.DaoMaster;
import com.lei.baweiliao.db.DaoSession;
import com.lei.baweiliao.threadhelper.ThreadHelper;
import com.lei.baweiliao.utils.Constants;
import com.lei.baweiliao.utils.SpUtils;
import com.lei.baweiliao.view.activity.AddTongxunActivity;
import com.lei.baweiliao.view.activity.ChatActivity;
import com.lei.baweiliao.view.activity.FriendActivity;
import com.lei.baweiliao.view.activity.GroupListActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class TongxunFragment extends EaseContactListFragment {
    private LinearLayout llContactInvite;
    private ImageView ivContactRed;//好友
    private LinearLayout llContactGroup;//群组
    private LocalBroadcastManager manager;


    private BroadcastReceiver BroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ivContactRed.setVisibility(View.VISIBLE);
            SpUtils.getInstance().add(SpUtils.IS_RED,true);
        }
    };

    private void refreshContact() {
        //获取联系人所有数据  从数据库中取出
        DaoMaster.DevOpenHelper user = new DaoMaster.DevOpenHelper(getContext(), "user");
        SQLiteDatabase writableDatabase = user.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(writableDatabase);
        DaoSession daoSession = daoMaster.newSession();
        daoSession.deleteAll(UserBean.class);
        ThreadHelper.getInstance().getExecutors().execute(()->{
            try {
                List<String> contacts = EMClient.getInstance().contactManager().getAllContactsFromServer();
                Log.e("ljl", "refreshContact: "+contacts.toString() );
                //校验
                if (contacts!=null&&contacts.size()>=0){
                    //设置数据
                    Map<String, EaseUser> contactMap=new HashMap<>();
                    //转换
                    for (String userInfo:contacts) {
                        daoSession.insert(new UserBean(null,userInfo,userInfo));
                        EaseUser easeUser=new EaseUser(userInfo);
                        contactMap.put(userInfo,easeUser);
                    }
                    setContactsMap(contactMap);
                    //刷新方法
                    refresh();
                }
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
        });

    }

    private void getContactFromHxServer() {
        ThreadHelper.getInstance().getExecutors().execute(() -> {
            try {
                List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                Log.e("ljl", "refreshContact: "+usernames.toString() );

                //校验
                if (usernames!=null&&usernames.size()>=0){
                    List<UserInfo>  contacts=new ArrayList<>();
                    //转换
                    for (String name:usernames){
                        UserInfo userInfo=new UserInfo(name);
                        contacts.add(userInfo);
                    }
                    //保存到本地数据库中 提供后期使用
//                        Model.getInstance().getDbManager().getContactTableDao().saveContacts(contacts,true);
                    if (getActivity()==null){
                        return;
                    }

                    //刷新页面
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //刷新页面的方法
                            refreshContact();
                        }
                    });
                }
            } catch (HyphenateException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        getContactFromHxServer();
        titleBar.setRightImageResource(R.drawable.em_add);
        View view = View.inflate(getActivity(),R.layout.fragment_tongxun,null);

        llContactInvite = (LinearLayout) view.findViewById(R.id.ll_contact_invite);
        ivContactRed = (ImageView) view.findViewById(R.id.iv_contact_red);
        llContactGroup = (LinearLayout) view.findViewById(R.id.ll_contact_group);
        listView.addHeaderView(view);

        EMClient.getInstance().contactManager().setContactListener(new EMContactListener() {

            @Override
            public void onContactInvited(String username, String reason) {
                //收到好友邀请
                getActivity().runOnUiThread(() -> {
                    ivContactRed.setVisibility(View.VISIBLE);
                });
            }

            @Override
            public void onFriendRequestAccepted(String username) {
                //好友请求同意
            }

            @Override
            public void onFriendRequestDeclined(String username) {
                //好友请求拒绝
            }

            @Override
            public void onContactDeleted(String username) {
                //被删除时回调此方法
            }


            @Override
            public void onContactAdded(String username) {
                //增加了联系人时回调此方法
            }
        });
        //listView联系人点击事件
        setContactListItemClickListener(user -> {
            Log.e("user",user.toString());
            if (user==null){
                return;
            }
            Intent intent=new Intent(getActivity(), ChatActivity.class);
            intent.putExtra(EaseConstant.EXTRA_USER_ID,user.getUsername());
            startActivity(intent);
        });

        llContactGroup.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), GroupListActivity.class));
        });
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        //初始化小红点
        Boolean isRed = (Boolean) SpUtils.getInstance().get(SpUtils.IS_RED,false);
        ivContactRed.setVisibility(isRed?View.VISIBLE:View.GONE);
        //添加按钮，点击事件
        titleBar.setRightLayoutClickListener(V ->
            startActivity(new Intent(getActivity(), AddTongxunActivity.class))
        );
        llContactInvite.setOnClickListener(V -> {
            ivContactRed.setVisibility(View.GONE);
            SpUtils.getInstance().add(SpUtils.IS_RED,false);
            //跳转到好友邀请页面
            startActivity(new Intent(getActivity(), FriendActivity.class));
        });

        manager = LocalBroadcastManager.getInstance(getContext());
        manager.registerReceiver(BroadcastReceiver,new IntentFilter(Constants.CONTACT_INVITE_CHANGED));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        manager.unregisterReceiver(BroadcastReceiver);
    }
}
